import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:my_flutter/util/toast_utils.dart';
import 'package:sp_util/sp_util.dart';
import 'package:my_flutter/res/constant.dart';
// import 'package:flutter_gen/gen_l10n/deer_localizations.dart';
import 'package:my_flutter/login/widgets/my_text_field.dart';
import 'package:my_flutter/res/resources.dart';
import 'package:my_flutter/routers/fluro_navigator.dart';
// import 'package:my_flutter/store/store_router.dart';
import 'package:my_flutter/util/change_notifier_manage.dart';
import 'package:my_flutter/util/other_utils.dart';
import 'package:my_flutter/widgets/my_app_bar.dart';
import 'package:my_flutter/widgets/my_button.dart';
import 'package:my_flutter/widgets/my_scroll_view.dart';

import '../login_router.dart';
import 'package:flutter_boost/flutter_boost.dart';

import 'package:flutter/gestures.dart';

import 'package:my_flutter/login/provider/login_page_provider.dart';

/// design/1注册登录/index.html
class LoginPage extends StatefulWidget {

  const LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage>
    with ChangeNotifierMixin<LoginPage> {
  //定义一个 TextEditingController 和FocusNode
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  final FocusNode _nodeText1 = FocusNode();
  final FocusNode _nodeText2 = FocusNode();
  bool _clickable = false;

  @override
  Map<ChangeNotifier?, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{//监听textField变化
     _nameController:callbacks,//给这两个控制器的变化 监听回调
      _passwordController:callbacks,
     _nodeText1 : null,//null 没有回调 不监听
     // _nodeText2 : null,//去掉也行
    };
  }

  // void _loginCallback(String name,Map args){
  //   return BoostChannel.instance.sendEventToNative(name,args);
  // }

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((timeStamp) {
      /// 显示状态栏和导航栏
      SystemChrome.setEnabledSystemUIOverlays([SystemUiOverlay.top,SystemUiOverlay.bottom]);
    });
    _nameController.text = SpUtil.getString(Constant.phone).nullSafe;
  }

  // @override
  // void dispose() {
  //   // TODO: implement dispose
  //   super.dispose();
  //
  //   // _loginCallBack();
  // }

  void _verify(){///账号密码判断
    final String name = _nameController.text;
    final String password = _passwordController.text;
    bool clicoable = true;
    if(name.isEmpty || name.length < 11){
      clicoable = false;
    }
    if(password.isEmpty || password.length < 6){
      clicoable = false;
    }

    /// 状态不一样再刷新，避免不必要的setState
    if(clicoable != _clickable){
      setState((){
        _clickable = clicoable;
      });
    }
  }

  void _login(){
    if(_nameController.text.length < 6){
      Toast.show('输入账号或手机号');
      return ;
    } else if(_passwordController.text.length < 6 ){
      Toast.show('输入6位以上的密码');
      return ;
    }
    // _loginCallback('login',
    //     {'phone':_nameController.text,'psw':_passwordController.text});
    BoostChannel.instance.sendEventToNative('login',
        {'phone':_nameController.text,'psw':_passwordController.text});

    SpUtil.putString(Constant.phone, _nameController.text); ///存储手机号
    // Toast.show('msg');
    // Navigator.pop(context);
    // NavigatorUtils.push(context, StoreRouter.auditPage);//Toast.show('登录');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        title: '登录',
        isBack: true,
        actionName: '验证码登录',
        onPressed: () {
          BoostNavigator.instance
              .push("smsLogin", withContainer: false);
          // NavigatorUtils.push(context, LoginRouter.smsLoginPage);
        },
      ),
      body: MyScrollView(
        keyboardConfig: Utils.getKeyboardActionsConfig(context, <FocusNode>[_nodeText1, _nodeText2]),
        padding: EdgeInsets.only(left: 16,right: 16,top: 20),
        children: _buildBody,
      ),
    );
  }

  List <Widget> get _buildBody =>  <Widget>[
    Text(
        '密码登录',
      // style: TextStyle.t,
    ),
    Gaps.vGap16,
    MyTextField(
      key: const Key('phone'),
        focusNode: _nodeText1,
        controller: _nameController,
      maxLength: 11,
      keyboardType: TextInputType.phone,
      hintText: '输入账号',
    ),
    Gaps.vGap8,
    MyTextField(
      key: Key('password'),
        keyName: 'password',
        focusNode: _nodeText2,
        isInputPwd: true,
        controller: _passwordController,
      keyboardType: TextInputType.visiblePassword,
      maxLength: 16,
      hintText: '输入密码',
    ),
    Gaps.vGap24,
    Container(
      alignment: Alignment.centerLeft,
      child: RichText(
        text: TextSpan(
          text: '同意',
          style: Theme.of(context).textTheme.subtitle2?.copyWith(fontSize: Dimens.font_sp14),
          children: <TextSpan>[
            TextSpan(
              text: '《用户协议》',
              style: TextStyle(
                color: Colors.blue,
              ),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  BoostNavigator.instance.push("webview", arguments:{
                    'title': '《用户协议》',
                    'url':'https://www.hqwx.com/aboutus/policy/user.html',
                  }, withContainer: false);
                },
            ),
            TextSpan(text: '和'),
            TextSpan(
              text: '《隐私协议》',
              style: TextStyle(
                color: Colors.blue,
              ),
              recognizer: TapGestureRecognizer()
                ..onTap = () {
                  BoostNavigator.instance.push("webview", arguments:{
                    'title': '《隐私协议》',
                    'url':'https://www.hqwx.com/aboutus/policy/hqwx.html',
                  }, withContainer: false);
                },
            ),
          ],
        ),
      ),
    ),
    Gaps.vGap24,
    MyButton(
      key: const Key('login'),
      onPressed: _clickable ? _login : null,
      text: '登录',
    ),
    Container(
      height: 40,
      alignment: Alignment.centerRight,
      child: GestureDetector(
      child: Text(
  '忘记密码',
        key: Key('forgotPassword'),
        style: Theme.of(context).textTheme.subtitle2,
      ),
        onTap: () => BoostNavigator.instance.push("resetPassword", withContainer: false),
            // NavigatorUtils.push(context, LoginRouter.resetPasswordPage),
      ),
    ),
    Gaps.vGap16,
    Container(
      alignment: Alignment.center,
      child: GestureDetector(
        child: Text(
  '没有注册',
          key: Key('noAccountRegister'),
          style: TextStyle(
            color: Theme.of(context).primaryColor,
          ),
        ),
        onTap: () =>  BoostNavigator.instance
            .push("register", withContainer: false),
            // NavigatorUtils.push(context, LoginRouter.registerPage),
      ),
    ),
  ];
}
